var passport = require('passport'),
    bcrypt = require('crypto');

var moment = require('moment'),
    BearerStrategy = require('passport-http-bearer').Strategy;
    // BasicStrategy = require('passport-http').BasicStrategy,
    // ClientPasswordStrategy = require('passport-oauth2-client-password').Strategy;
var crypto  = require('crypto');
// var pg = require('../lib/pgClient');
const settings = require('../config/settings');
const redisClient = require('../lib/redisClient');

passport.serializeUser(function(user, done) {
    done(null, user.id);
});

passport.deserializeUser(function(id, done) {
    User.findOne({ id: id }, function(err, user) {
        done(err, user);
    });
});

/**
 * BearerStrategy
 *
 * This strategy is used to authenticate users based on an access token (aka a
 * bearer token).  The user must have previously authorized a client
 * application, which is issued an access token to make requests on behalf of
 * the authorizing user.
 */
passport.use(new BearerStrategy(
    function(accessToken, done) {

        redisClient.get(accessToken, function(err, token){
            if (err) {
                return done(err);
            }
            token = JSON.parse(token);
            if (!token) {
                return done(null, false);
            }
            /*var now = moment().unix();
            var creationDate = moment(token.createdAt).unix();

            if (now - creationDate > settings.oauth_conf.tokenLife) {
                console.log('Token expired');
                return done(null, false, { message: 'Token expired' });
            }*/

            done(err, token.user, token.scopes);

        });
    }
));
